#![allow(unused)]

use std::ffi::CString;
use std::ptr::null_mut;
use oh_napi::*;


fn helper_add(a: i32, b: i32) -> error::Result<i32> {
    Ok(a + b)
}

extern "C" fn add(env: napi_env, info: napi_callback_info) -> napi_value {
    unsafe {
        let env = Env::from(env);

        let args = try_to!(env, env.get_args(info));

        let a = try_to!(env, env.get_int32_from(args[0]));
        let b = try_to!(env, env.get_int32_from(args[1]));
        let c = try_to!(env, helper_add(a, b));

        try_to!(env, env.create_int32(c))
    }
}



extern "C" fn vec_add(env: napi_env, info: napi_callback_info) -> napi_value {
    unsafe {
        let env = Env::from(env);

        let args = try_to!(env, env.get_args(info));


        null_mut()
    }
}

type Callback = extern "C" fn(env: napi_env, info: napi_callback_info) -> napi_value;

unsafe fn new_func_descriptor(name: &'static str, f: Callback) -> napi_property_descriptor {
    let name = CString::new(name).unwrap();
    napi_property_descriptor {
        utf8name: CString::into_raw(name),
        name: null_mut(),
        method: Some(f),
        getter: None,
        setter: None,
        value: null_mut(),
        attributes: napi_property_attributes_napi_default,
        data: null_mut(),
    }
}


#[ctor]
fn register_hello_module() {
    let mut name_vec = "hello".to_string().into_bytes();
    name_vec.push(0);

    let mut hello_module = napi_module {
        nm_version: 1,
        nm_flags: 0,
        nm_filename: null_mut(),
        nm_register_func: Some(init),
        nm_modname: name_vec.as_ptr() as _,
        nm_priv: 0 as *mut _,
        reserved: [0 as *mut _; 4],
    };


    unsafe {
        napi_module_register(&mut hello_module);
    }

    // Init将在exports上挂上Add/NativeCallArkTS这些Native方法，此处的exports就是开发者import之后获取到的ArkTS对象。
    unsafe extern "C" fn init(env: napi_env, exports: napi_value) -> napi_value {
        let desc = [
            new_func_descriptor("add", add),
        ];

        let count = desc.len();
        napi_define_properties(env, exports, count as size_t, desc.as_ptr());
        exports
    }
}


